<?php

namespace common\models;

use Yii;
use common\helpers\Util;

/**
 * This is the model class for table "EmploymentPause".
 */
class EmploymentAppeal extends ActiveRecord {

    const SnPrefix = 'EA';

    // 申诉理由
    const HandlerDesigner = 1;
    const HandlerEmployer = 2;
    public static $handlerSelector = [
        self::HandlerDesigner => '设计师',
        self::HandlerEmployer => '雇主',
    ];

    // 申诉理由
    const ReasonAttitude = 1;
    const ReasonAbility = 2;
    public static $reasonSelector = [
        self::ReasonAttitude => '态度恶劣',
        self::ReasonAbility => '能力不足',
    ];

    // @name 日志操作人类型定义
    const StatusInit = 0;
    const StatusAccept = 1;
    const StatusSuccess = 10;
    const StatusRefuse = 11;
    public static $statusSelector = [
        self::StatusInit => ['title' => '待处理', 'status' => 'gray'],
        self::StatusAccept => ['title' => '已受理', 'status' => 'blue'],
        self::StatusSuccess => ['title' => '已完成', 'status' => 'green'],
        self::StatusRefuse => ['title' => '已拒绝', 'status' => 'red'],
    ];

    // only define rules for those attributes that
    // will receive user inputs.
    public function rules()
    {
        return [
            [['order_number', 'employment_id', 'handler', 'designer_id', 'employer_id', 'reason', 'describe'], 'required'],
            [['employment_id', 'designer_id', 'employer_id', 'reason', 'handler', 'status', 'operator', 'deleted_at'], 'integer'],
            [['order_number'], 'string', 'max' => 32],
            [['describe', 'remark'], 'string', 'max' => 1024],
            [['uploads'], 'string', 'max' => 16384],
        ];
    }
    /**
     * @name 字段名称
     * @return array
     */
    public function attributeLabels()
    {
        return [
            'order_number' => '案例编号',
            'employment_id' => '雇佣编号',
            'handler' => '申诉类型',
            'designer_id' => '设计师',
            'employer_id' => '雇主',
            'reason' => '原因',
            'uploads' => '上传资料',
            'status' => '状态',
            'operator' => '受理人',
            'describe' => '描述',
            'remark' => '备注',
            'deleted_at' => '删除时间',
        ];
    }
    /**
     * @name update & insert data check config for html
     * @param $reason string 操作类型
     * @param $encodeJson boolean 是否转成JSON字符串
     * @return array
     */
    public static function flyer($reason = 'insert')
    {
        return [
            'param' => [
                'employment_id' => ['雇佣编号', ['int', 'required']],
                'describe' => ['描述', ['maxlength' => 1024, 'required']],
            ],
        ];
    }

    /**
     * @name 获取user信息
     * @return \yii\db\ActiveQuery
     */
    public function getDesigner()
    {
        return $this->hasOne(User::className(), ['id' => 'designer_id']);
    }

    /**
     * @name 获取employer信息
     * @return \yii\db\ActiveQuery
     */
    public function getEmployer()
    {
        return $this->hasOne(User::className(), ['id' => 'employer_id']);
    }

    /**
     * @name 获取employer信息
     * @return \yii\db\ActiveQuery
     */
    public function getEmployment()
    {
        return $this->hasOne(Employment::className(), ['id' => 'employment_id']);
    }

    /**
     * @name 判断是否可以处理
     * @return boolean
     */
    public function canSettle()
    {
        if($this->deleted()) {
            return false;
        }
        if(in_array($this->status, [static::StatusInit, static::StatusAccept])) {
            return true;
        }
        return false;
    }

    /**
     * 申诉成功
     * @return boolean
     */
    public function accept()
    {
        if( ! in_array($this->status, [static::StatusInit])) {
            return false;
        }
        $this->status = static::StatusAccept;
        $this->updated_at = time();
        $this->operator = Yii::$app->admin->id;
        return $this->save();
    }

    /**
     * 申诉成功
     * @return boolean
     */
    public function success()
    {
        if( ! in_array($this->status, [static::StatusInit, static::StatusAccept])) {
            return false;
        }
        $this->status = static::StatusSuccess;
        $this->updated_at = time();
        $this->operator = Yii::$app->admin->id;
        return $this->transaction(function ($db) {
            if( ! $this->save()) {
                throw new \Exception('update appeal status error');
            }
            if( ! $this->employment->abort()) {
                throw new \Exception('abort employment status error');
            }
            return true;
        });
    }

    /**
     * 拒绝申诉
     * @return boolean
     */
    public function refuse()
    {
        if( ! in_array($this->status, [static::StatusInit, static::StatusAccept])) {
            return false;
        }
        $this->status = static::StatusRefuse;
        $this->updated_at = time();
        $this->operator = Yii::$app->admin->id;
        return $this->save();
    }

    /**
     * 创建暂停订单
     * @return mixed
     */
    public static function creator($params)
    {
        if(empty($params)) {
            return false;
        }
        $appeal = new static();
        $appeal->order_number = static::generateOrderNumber();
        $appeal->loads($params);
        $appeal->status = static::StatusInit;
        $appeal->operator = 0;
        if( ! ($appeal->validate() && $appeal->save())) {
            return false;
        }
        return $appeal;
    }

    /**
     * 生成订单号
     * @return string
     */
    public static function generateOrderNumber()
    {
        return strtoupper(static::SnPrefix.base_convert((microtime(true) * 10000).rand(10000, 99999).rand(10000, 99999), 10, 36));
    }
}